package com.zxstudio.bulls.trade.oauth.service;

import com.zxstudio.bulls.stock.common.utils.GlobalConstants;
import com.zxstudio.bulls.stock.entity.user.TradeUser;
import com.zxstudio.bulls.trade.oauth.bo.OAuthTradeUser;
import com.zxstudio.bulls.trade.oauth.repository.TradeUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("authStockUserDetailService")
public class AuthStockUserDetailServiceImpl implements UserDetailsService {

    /**
     * 用户
     */
    @Autowired
    private TradeUserRepository tradeUserRepository;

    @Autowired
    private CacheManager cacheManager;

    @Override
    public UserDetails loadUserByUsername(String userNo) throws UsernameNotFoundException {

        // 查询缓存
        Cache cache = cacheManager.getCache(GlobalConstants.OAUTH_KEY_STOCK_USER_DETAILS);
        if (cache != null && cache.get(userNo) != null) {
            return (UserDetails) cache.get(userNo).get();
        }
        // 缓存未找到， 查询数据库
        TradeUser tradeUser = tradeUserRepository.findByUserNo(userNo);;
        if(null == tradeUser){
            throw new UsernameNotFoundException(userNo  + " not valid !");
        }
        // 封装成OAUTH鉴权的用户对象
        UserDetails userDetails = new OAuthTradeUser(tradeUser);
        // 将用户信息放入缓存
        cache.put(userNo, userDetails);
        return userDetails;
    }
}

